import { PlusOutlined } from '@ant-design/icons';
import type {
  ActionType,
  ProColumns,
  ProDescriptionsItemProps,
} from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProDescriptions,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl, useRequest } from '@umijs/max';
import { Button, Drawer, message, Select, Space, Spin } from 'antd';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { getEmployeeList, removeEmployee, getMembers } from '@/services/ant-design-pro/employee';

// 定义员工数据类型
interface Employee {
  imei: string;
  nickName: string;
  sex: '男' | '女';
  age?: number;
  jobPost?: string;
  jobDutyName?: string;
  member?: '是' | '否';
  departName?: string;
}

// 定义客户数据类型
interface Customer {
  id: number;
  name: string;
}

// 自定义防抖函数
function useDebounce<T>(value: T, delay: number): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedValue(value);
    }, delay);

    return () => {
      clearTimeout(timer);
    };
  }, [value, delay]);

  return debouncedValue;
}

// 调用客户搜索API
const searchCustomers = async (keyword: string): Promise<Customer[]> => {
  console.log('搜索客户:', keyword);
  try {
    // 调用真实API
    const response = await getMembers({ departName: keyword });
    // 假设API返回的数据结构需要转换为我们需要的格式
    if (response && response) {
      return response.map((item: any) => ({
        id: item.id || item.memberId,
        name: item.name || item.memberName,
      }));
    }
    return [];
  } catch (error) {
    console.error('搜索客户出错:', error);
    return [];
  }
};

const EmployeeList: React.FC = () => {
  const actionRef = useRef<ActionType>(null);
  const intl = useIntl();
  
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<Employee>();
  const [selectedRowsState, setSelectedRows] = useState<Employee[]>([]);
  const [selectedCustomerId, setSelectedCustomerId] = useState<number>(); // 默认客户ID
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [searchLoading, setSearchLoading] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>('');
  
  // 使用自定义防抖hook处理搜索文本
  const debouncedSearchText = useDebounce(searchText, 500);
  
  // 当防抖后的搜索文本变化时执行搜索
  useEffect(() => {
    const fetchCustomers = async () => {
      if (debouncedSearchText.length >= 2) {
        setSearchLoading(true);
        try {
          const data = await searchCustomers(debouncedSearchText);
          setCustomers(data);
        } finally {
          setSearchLoading(false);
        }
      }
    };
    
    fetchCustomers();
  }, [debouncedSearchText]);

  const [messageApi, contextHolder] = message.useMessage();

  const { run: delRun, loading } = useRequest(removeEmployee, {
    manual: true,
    onSuccess: () => {
      setSelectedRows([]);
      actionRef.current?.reloadAndRest?.();
      messageApi.success('删除成功，即将刷新');
    },
    onError: () => {
      messageApi.error('删除失败，请重试');
    },
  });

  // 定义表格列
  const columns: ProColumns<Employee>[] = [
    {
      title: '姓名',
      dataIndex: 'nickName',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '设备号',
      dataIndex: 'imei'
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueEnum: {
        '男': { text: '男', status: 'Processing' },
        '女': { text: '女', status: 'Default' },
      },
    },
    {
      title: '年龄',
      dataIndex: 'age',
      hideInSearch: true,
    },
    {
      title: '岗位',
      dataIndex: 'jobPost',
      valueEnum: {
        '开发': { text: '开发', status: 'Processing' },
        '测试': { text: '测试', status: 'Default' },
        '产品': { text: '产品', status: 'Success' },
        '设计': { text: '设计', status: 'Warning' },
        '运营': { text: '运营', status: 'Error' },
      },
    },
    {
      title: '职责',
      dataIndex: 'jobDutyName',
    },
    {
      title: '是否会员',
      dataIndex: 'member',
      valueEnum: {
        '是': { text: '是', status: 'Success' },
        '否': { text: '否', status: 'Default' },
      },
    },
    {
      title: '部门',
      dataIndex: 'departName',
    },

    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            message.info('编辑功能待实现');
          }}
        >
          <FormattedMessage id="pages.searchTable.edit" defaultMessage="编辑" />
        </a>,
        <a
          key="delete"
          onClick={async () => {
            await handleRemove([record]);
            actionRef.current?.reload();
          }}
        >
          <FormattedMessage id="pages.searchTable.delete" defaultMessage="删除" />
        </a>,
      ],
    },
  ];

  /**
   * 删除员工
   * 
   * @param selectedRows
   */
  const handleRemove = useCallback(
    async (selectedRows: Employee[]) => {
      if (!selectedRows?.length) {
        messageApi.warning('请选择删除项');
        return;
      }

      await delRun(selectedRows.map((row) => row.imei));
    },
    [delRun, messageApi],
  );

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<Employee>
        headerTitle={
        <Space>
          <span>客户：</span>
          <Select
            value={selectedCustomerId}
            style={{ width: 200 }}
            showSearch
            placeholder="输入至少2个字符搜索"
            defaultActiveFirstOption={false}
            filterOption={false}
            onSearch={(value) => setSearchText(value)}
            onChange={(value) => {
              setSelectedCustomerId(value);
              actionRef.current?.reload();
            }}
            notFoundContent={loading ? <Spin size="small" /> : null}
          >
            {customers.map(customer => (
              <Select.Option key={customer.id} value={customer.id}>
                {customer.name}
              </Select.Option>
            ))}
          </Select>
        </Space>
      }
        actionRef={actionRef}
        rowKey="imei"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              messageApi.success('添加员工');
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          // 使用选定的客户ID
          const response = await getEmployeeList({
            ...params,
            memberId: selectedCustomerId ?? 0,
          });
          
          // 适配后端返回的数据结构
          console.log('response', response);
          return {
            data: response?.data|| [],
            success: response.code === 200,
            total: response?.data?.length || 0,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a> 项
            </div>
          }
        >
          <Button
            loading={loading}
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reload();
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
          <Button type="primary">
            <FormattedMessage id="pages.searchTable.batchApproval" defaultMessage="批量审批" />
          </Button>
        </FooterToolbar>
      )}

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.nickName && (
          <ProDescriptions<Employee>
            column={2}
            title={currentRow?.nickName}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.imei,
            }}
            columns={columns as ProDescriptionsItemProps<Employee>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default EmployeeList;